﻿document.write('<script src="http://connect.facebook.net/en_US/all.js"></script>');
var FB_LoginUrl= 'http://www.facebook.com/dialog/oauth?client_id=579561022109158&redirect_uri=http://www.c2life.com.vn/smart_phone/OpenId&response_type=token&display=popup&scope=email,manage_pages,photo_upload,publish_actions,publish_stream,read_friendlists,status_update,user_birthday,user_photos,user_status,video_upload';
var windowInvite;
function FB_LOGIN(){
    window.location = FB_LoginUrl;    
}

function check_info()
{
    var url = root + 'smart_phone/view_check_login';
                $.post(url,{
                },
                function(data){
                   if(data == "false")
                   {
                        FB_LOGIN();
                   }
                   else
                   {
                        checkFirstTime();
                   }

                });
       return false;
}
function checkFirstTime(){
   
      var url = root + 'smart_phone/view_check_first_time';
                $.post(url,{
                },
                function(data){
                   if(data == "true")
                   {
                        getInfo();
                   }
                   if(data == "false")
                   {
                       nex_page(1);
                   }
                });
                return false;
}
function getInfo()
{
     var url = root + 'smart_phone/view_get_info';
                $.post(url,{
                },
                function(data){
                   if(data)
                   {
                        $(".tab-register").html(data);
                        nex_page(2);
                       
                   }
                });
                return false;
}
function select_link()
{
    var url = root + 'smart_phone/view_code';
    var type =$(".check_value").val();
    $.post(url,{ type:type
                },
                function(data){
                   if(data)
                   {
                        $(".tab-noti").html(data);
                        nex_page(0);
                       
                   }
                });
    return false;
}
function update_info()
{
    var fullname =$(".fullname").val();
    var phone =$(".phone").val();
    var email =$(".email").val();
    var url = root + 'smart_phone/view_update_info';
    $.post(url,{ fullname:fullname,phone:phone
                },
                function(data){
                   if(data == "true")
                   {
                        nex_page(1);
                   }
                });
    return false;
}
// global properties
var stage;
var currentTick = 0;
var arrayImages = new Array();
var loadedImgNumber = 0;

// for welcome screen
var loadingC2Img;
var loadingTextImg;
var loadingMusicImg;

// for other screen
var stageSprite;
var topLightImgs;
var logoSprite;
var welcomeCha;
var tvcCha;

// for character lap
var welcomeLapSpite;
var tvcStartSpite;
var tvcLapSpite;

var tickTVC = -1;


// audio
var myCirclePlayer;
var myOtherOne;
/**
* Init handler
*/

$(document).ready(function () {
    log("Width: " + window.innerWidth + " - Height: " + window.innerHeight + "- Ratio: " + window.devicePixelRatio);

    if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
        var msViewportStyle = document.createElement("style");
        msViewportStyle.appendChild(
            document.createTextNode(
                "@-ms-viewport{width:auto!important}"
            )
        );
        document.getElementsByTagName("head")[0].
            appendChild(msViewportStyle);
    }

    initLoadingScreen();

    $("#btnHome").click(welcomeVideoStart);
    $("#btnVideo").click(tvcVideoStart);
    $("#btnMusic").click(fullsongVideoStart);
    $("#btnShare").click(showshareStart);
	$('#page-mp3').html('<img src="'+ root +'static/images/mobile/videotrangmp3_07504.gif" alt="" width="430" height="450" />').hide();
	$("#sound-welcom").jPlayer({
		ready: function (event) {
			$(this).jPlayer("setMedia", {
				m4a: root + "static/images/mobile/Welcome.m4a",
				oga: root + "static/images/mobile/Welcome.ogg"
			});
		},
		swfPath: "js",
		supplied: "m4a, oga",
		wmode: "window",
		smoothPlayBar: true,
		keyEnabled: true,
		nativeSupport: true,
		oggSupport: false,
		loop: true,
		customCssIds: true
	});
	$("#sound-mp3").jPlayer({
		ready: function (event) {
			$(this).jPlayer("setMedia", {
				m4a: root + "static/images/mobile/videotrangmp3.mp3",
				oga: root + "static/images/mobile/videotrangmp3.ogg"
			});
		},
		swfPath: "js",
		supplied: "m4a, oga",
		wmode: "window",
		smoothPlayBar: true,
		keyEnabled: true,
		nativeSupport: true,
		oggSupport: false,
		loop: true,
		customCssIds: true
	});
	
	$("#btnNext").click(function () {
		$(".buttonNext").hide();
        startMainScreen();
		$("#sound-welcom").jPlayer("play");
        $('#welcom').html('<img src="'+ root +'static/images/mobile/Welcome.gif" alt="" width="306" height="500" />');
    });
	
	$('.btn-video').on('click',function(){
		$(this).removeClass('unactive').addClass('active');
		$('.btn-zing').removeClass('active').addClass('unactive');
        $(".check_value").val("1");
	});
	
	$('.btn-zing').on('click',function(){
		$(this).removeClass('unactive').addClass('active');
		$('.btn-video').removeClass('active').addClass('unactive');
        $(".check_value").val("2");
	});
	
	$(window).load(function(){
		// var myScroll = new iScroll('iscroll-giaithuong');
		// myScroll_1 = new iScroll('iscroll-week-1');
		// myScroll_2 = new iScroll('iscroll-week-2');
		// myScroll_3 = new iScroll('iscroll-week-3');
		// myScroll_4 = new iScroll('iscroll-week-4');
	});
	
	$('.btn-week').on('click',function(){
		if($(this).hasClass('disable') || $(this).hasClass('active')){
			return false;
		}
		$('.btn-week').removeClass('active');
		$(this).addClass('active');
		var index = $('.btn-week').index(this) + 1;
		$('.iscroll-week').hide();
		$('#iscroll-week-'+index).show();
		return false;
	});
});
var ischeck = true;
var ischeck1 = true;
function nex_page(id){
	$('.content-share > div').hide();
	$('.content-share > div').eq(id).show();
	if(!$('.tab-giaithuong').is(':hidden') && ischeck){
		var myScroll = new iScroll('iscroll-giaithuong');
		ischeck = false;
	}
}




/**
* Init welcome handler
*/

function initLoadingScreen() {
    arrayImages[0] = new Image();
    arrayImages[0].onload = handleLoadingImageLoad;
    arrayImages[0].onerror = handleImageError;
    arrayImages[0].src = root + "static/images/mobile/Chai_C2.png";

    arrayImages[1] = new Image();
    arrayImages[1].onload = handleLoadingImageLoad;
    arrayImages[1].onerror = handleImageError;
    arrayImages[1].src = root + "static/images/mobile/music.png";

    arrayImages[2] = new Image();
    arrayImages[2].onload = handleLoadingImageLoad;
    arrayImages[2].onerror = handleImageError;
    arrayImages[2].src = root + "static/images/mobile/loading.png";
}


/**
* Handle loading image for welcome
*/
function handleLoadingImageLoad(e) {
    loadedImgNumber++;

    if (loadedImgNumber == 3) {
        startWelcomeScreen();
    }
}


/**
* Handle loading error
*/
function handleImageError(e) {
    log("Error Loading Image : " + e.target.src);
}


/**
* Initilale Welcome Screen
*/
function startWelcomeScreen() {
    $(".buttons").show();
    $(".loading").hide();
    var canvas = document.getElementById("canvas");
    stage = new createjs.Stage(canvas);

    loadingC2Img = new createjs.Bitmap(arrayImages[0]);
    loadingC2Img.regX = 85;
    loadingC2Img.regY = 460;
    loadingC2Img.x = 320;
    loadingC2Img.y = 650;
    stage.addChild(loadingC2Img);

    loadingMusicImg = new createjs.Bitmap(arrayImages[1]);
    loadingMusicImg.regX = 85;
    loadingMusicImg.regY = 217;
    loadingMusicImg.x = 320;
    loadingMusicImg.y = 150;
    stage.addChild(loadingMusicImg);

    loadingTextImg = new createjs.Bitmap(arrayImages[2]);
    loadingTextImg.regX = 87;
    loadingTextImg.regY = 30;
    loadingTextImg.x = 320;
    loadingTextImg.y = 150;
    stage.addChild(loadingTextImg);

    createjs.Ticker.setFPS(12);
    createjs.Ticker.addEventListener("tick", tickLoading);

    initMainScreen();
}


/**
* Tick Handler
*/
var angle = 5;
function tickLoading() {
    currentTick += 1;
    loadingC2Img.rotation += angle;
    if (loadingC2Img.rotation == 10)
        angle = -5;
    else if (loadingC2Img.rotation == -10)
        angle = 5;

    if (loadingMusicImg.y > 0)
        loadingMusicImg.y -= 13;
    else {
        if (currentTick == 1) {
            loadingMusicImg.y = 150;
        }
    }


    if (currentTick > 12)
        currentTick = 0;
    stage.update();
}


/**
* Handle loading image for main stage
*/
function initMainScreen() {
    arrayImages[3] = new Image();
    arrayImages[3].onload = handleImageLoad;
    arrayImages[3].onerror = handleImageError;
    arrayImages[3].src = root + "static/images/mobile/light.png";

    arrayImages[4] = new Image();
    arrayImages[4].onload = handleImageLoad;
    arrayImages[4].onerror = handleImageError;
    arrayImages[4].src = root + "static/images/mobile/logo.png";

    arrayImages[5] = new Image();
    arrayImages[5].onload = handleImageLoad;
    arrayImages[5].onerror = handleImageError;
    arrayImages[5].src = root + "static/images/mobile/stage.png";
    
    arrayImages[6] = new Image();
    arrayImages[6].onload = handleImageLoad;
    arrayImages[6].onerror = handleImageError;
    arrayImages[6].src = root + "static/images/mobile/welcome_lap_SH.png";
    
    arrayImages[7] = new Image();
    arrayImages[7].onload = handleImageLoad;
    arrayImages[7].onerror = handleImageError;
    arrayImages[7].src = root + "static/images/mobile/startTvc_S.png";
    
    arrayImages[8] = new Image();
    arrayImages[8].onload = handleImageLoad;
    arrayImages[8].onerror = handleImageError;
    arrayImages[8].src = root + "static/images/mobile/tvclap.png";
	
	arrayImages[9] = new Image();
    arrayImages[9].onload = handleImageLoad;
    arrayImages[9].onerror = handleImageError;
    arrayImages[9].src = root + "static/images/mobile/Welcome.gif";
	
	arrayImages[10] = new Image();
    arrayImages[10].onload = handleImageLoad;
    arrayImages[10].onerror = handleImageError;
    arrayImages[10].src = root + "static/images/mobile/videotrangmp3_07504.gif";
	tvcSound =new mProton.Sound(root + "static/images/mobile/tvc.mp3", 0, handleImageLoad);
	
}



/**
* Handle loading image for main stage
*/
function handleImageLoad(e) {
    loadedImgNumber++;

    if (loadedImgNumber == 11) {
        reset();
        $(".buttonNext").show();
    }
}


/**
* Initilale Main Screen
*/
function startMainScreen() {
    reset();
    stage = new createjs.Stage(canvas);

    log("Start main stage");
    
    log("Add stage");
    var stageSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[5]],
        //width, height & registration point of each sprite
        frames: [
            [0, 1, 1020, 120],
            [0, 1, 1020, 120],
            [0, 1, 1020, 120],
            [0, 121, 1020, 120],
            [0, 121, 1020, 120],
            [0, 121, 1020, 120],
            [0, 241, 1020, 120],
            [0, 241, 1020, 120],
            [0, 241, 1020, 120],
            [0, 361, 1020, 120],
            [0, 361, 1020, 120],
            [0, 361, 1020, 120]
        ],
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            stageanimation: [0, 11, "stageanimation"]
        }
    });
    stageSprite = new createjs.BitmapAnimation(stageSpriteSheet);
    stageSprite.x = -194;
    stageSprite.y = 607;
    stageSprite.gotoAndPlay("stageanimation");
    stage.addChild(stageSprite);


    log("Add light");
    topLightImgs = new Array();
    var positionLeft = 110;
    for (var i = 0; i < 3; i++) {
        topLightImgs[i] = new createjs.Bitmap(arrayImages[3]);
        topLightImgs[i].regX = 225;
        topLightImgs[i].regY = 13;
        topLightImgs[i].x = positionLeft;
        topLightImgs[i].y = -80;
        topLightImgs[i].scaleX = 1.3;
        topLightImgs[i].scaleY = 1.3;
        positionLeft += 210;
        stage.addChild(topLightImgs[i]);
    }


    log("Add logo");
    var logoSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[4]],
        //width, height & registration point of each sprite
        frames: [
            [0, 0, 227, 386],
            [227, 0, 227, 386],
            [454, 0, 227, 386],
            [681, 0, 227, 386],
            [908, 0, 227, 386],
            [1135, 0, 227, 386],
            [1362, 0, 227, 386],
            [1599, 0, 227, 386]
        ],
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            stay: {
                frames: [0],
                next: "run",
                frequency: 2
            },
            run: {
                frames: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]
            }
        }
    });
    logoSprite = new createjs.BitmapAnimation(logoSpriteSheet);
    logoSprite.x = 18;
    logoSprite.y = 18;
    logoSprite.gotoAndPlay("run");
    stage.addChild(logoSprite);

    
    log("Add Welcome lap character");
    var welcomeLapSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[6]],
        //width, height & registration point of each sprite
        frames: { width: 139, height: 250, regX: 0, regY: 0, count: 110 },
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            lap: [0, 110, "lap"]
        }
    });
    welcomeLapSpite = new createjs.BitmapAnimation(welcomeLapSpriteSheet);

    welcomeLapSpite.x = 220;
    welcomeLapSpite.y = 290;
    welcomeLapSpite.scaleX = 1.5;
    welcomeLapSpite.scaleY = 1.5;
    welcomeLapSpite.gotoAndStop("lap");
    welcomeLapSpite.visible = false;
    stage.addChild(welcomeLapSpite);
    

    log("Add tvc Start character");
    var tvcStartSpriteSheet = new createjs.SpriteSheet({
        images: [arrayImages[7]],
        frames: { width: 233, height: 250.5, regX: 0, regY: 0, count: 64 },
        animations: {
            walk: [0, 64]
        }
    });
    tvcStartSpite = new createjs.BitmapAnimation(tvcStartSpriteSheet);

    tvcStartSpite.x = 250;
    tvcStartSpite.y = 240;
    tvcStartSpite.scaleX = 1.8;
    tvcStartSpite.scaleY = 1.8;
    tvcStartSpite.gotoAndStop("walk");
    tvcStartSpite.visible = false;
    stage.addChild(tvcStartSpite);
    

    var tvcLapSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[8]],
        //width, height & registration point of each sprite
        frames: { width: 66, height: 250, regX: 0, regY: 0, count: 117 },
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            lap: [0, 115]
        }
    });
    tvcLapSpite = new createjs.BitmapAnimation(tvcLapSpriteSheet);

    tvcLapSpite.x = 530;
    tvcLapSpite.y = 290;
    tvcLapSpite.scaleX = 1.5;
    tvcLapSpite.scaleY = 1.5;
    tvcLapSpite.gotoAndStop("lap");
    tvcLapSpite.visible = false;
    stage.addChild(tvcLapSpite);

    

    createjs.Ticker.setFPS(8);
    createjs.Ticker.addEventListener("tick", tickHandle);

    setActiveTab($("#btnHome"));
    
    //var introVideo = document.getElementById("welcomeVideo");
    //var bitmap = new createjs.Bitmap(introVideo);
    //bitmap.x = 0;
    //bitmap.y = 300;
    //bitmap.scaleX = 0.5;
    //bitmap.scaleY = 0.5;
    //stage.addChild(bitmap);

    // welcomeVideoStart();
}


/**
* Tick Handler
*/
var lightAngle = 2;
function tickHandle() {
	console.log('111');
    currentTick += 1;


    topLightImgs[0].rotation += lightAngle;
    topLightImgs[1].rotation -= lightAngle / 2;
    topLightImgs[2].rotation -= lightAngle;

    if (topLightImgs[0].rotation == 10)
        lightAngle = -2;
    else if (topLightImgs[0].rotation == -10)
        lightAngle = 2;



    if (currentTick > 8)
        currentTick = 0;
    

    if (tickTVC > -1) {
        tickTVC += 1;
        if (tickTVC == 54) {
            
        }
        else if (tickTVC == 60) {
                logoSprite.visible = false;
				showVideo("tvcVideo", tvcVideoEnd);
            }
        else if (tickTVC == 64) {
            tvcStartSpite.visible = false;
            tvcStartSpite.stop();
            tickTVC = -1;
            
            document.getElementById("tvcVideo").play();
            
        }
        
    }
    stage.update();
}





/**
* Set tab active
*/
function setActiveTab(button) {
    $(".buttons button").removeClass("active");
    $(button).addClass("active");
}


/**
* Reset
*/
function reset() {
    stage.removeAllChildren();
    createjs.Ticker.removeAllListeners();
    stage.update();
}
 

/**
* log message
*/
function log(message) {
    console.log(message);
    $("#message").html(message);
}

function showwelcom() {
	logoSprite.visible = true;
	$('#welcom').show();
    $("video").removeClass("videoActive");
	$("#sound-welcom").jPlayer("play");
	$('#welcom img').attr('src',root + 'static/images/mobile/Welcome.gif');
}

function showmp3() {
	logoSprite.visible = true;
	$('#page-mp3').show();
    $("video").removeClass("videoActive");
	$("#sound-mp3").jPlayer("play");
	$('#page-mp3 img').attr('src',root + 'static/images/mobile/videotrangmp3_07504.gif');
}

function showVideo(videoid, nextFunction) {
    $("video").removeClass("videoActive");
    var video = document.getElementById(videoid);
    $(video).addClass("videoActive");
    
    droidfix.init(video);
    video.addEventListener("abort", nextFunction);
    droidfix.addEndListener(nextFunction);
}

function showshare(){
	logoSprite.visible = false;
	$('#tvcVideo').removeClass('videoActive');
	$('.content-share').show();
}


function welcomeVideoStart() {
    pauseVideos();
	showwelcom();
    setActiveTab($("#btnHome"));
}

function showshareStart(){
	pauseVideos();
    setActiveTab($("#btnShare"));
	showshare();
	if(!$('.tab-rules').is(':hidden') && ischeck1){
		var myScroll_1 = new iScroll('iscroll_rules');
		ischeck1 = false;
	}
}

function tvcVideoStart() {
    pauseVideos();
    setActiveTab($("#btnVideo"));
    $("video").removeClass("videoActive");
    tvcStartSpite.visible = true;
    tvcStartSpite.play();
    tickTVC = 0;
	tvcSound.play();
}

function fullsongVideoStart() {
	pauseVideos();
    setActiveTab($("#btnMusic"));
    showmp3();
}

function welcomeVideoEnd() {
    log("Welcome video end");
    $("#welcomeVideo").removeClass("videoActive");
    welcomeLapSpite.visible = true;
    welcomeLapSpite.play();

}

function tvcVideoEnd() {
    log("TVC video end");
}

function fullsongVideoEnd() {
    log("Fullsong video end");
}

function pauseVideos() {
    $("#sound-welcom").jPlayer("stop");
	$('#welcom img').attr('src',root + 'static/images/mobile/blank.gif');
	$("#sound-mp3").jPlayer("stop");
	$('#page-mp3 img').attr('src',root + 'static/images/mobile/blank.gif');
	document.getElementById("tvcVideo").pause();
    tvcStartSpite.visible = false;
    tvcStartSpite.stop();
    tickTVC = -1;
	tvcSound.stop();
	$('.content-share').hide();
}